package com.atguigu.educenter.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.util.ConstantPropertiesUtil;
import com.atguigu.educenter.util.HttpClientUtils;
import com.atguigu.servicebase.exception.EduException;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * create by: zr
 * description: TODO
 * create time: 2021/11/23 14:56
 *
 * @author zr
 * @Param: null
 * @return
 */
//注意这里没有配置 @RestController
//@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Autowired
    private ConstantPropertiesUtil constantPropertiesUtil;
    @Autowired
    private UcenterMemberService ucenterMemberService;

    /**
     * 获取扫描人的信息  添加数据
     *
     * @return
     */
    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) {
        // 得到授权临时票据code
        //从redis中将state获取出来，和当前传入的state作比较
        //如果一致则放行，如果不一致则抛出异常：非法访问
        // 拿着code请求微信的固定地址 得到access_token 和openId
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        // 拼接三个参数 id 秘钥和code
        String accessTokenUrl = String.format(baseAccessTokenUrl, constantPropertiesUtil.getAppId(),
                constantPropertiesUtil.getAppSecret(), code);
        // 请求拼接好的地址 得到access_token 和openId
        // 使用httpclient 发送请求 得到返回结果
        String accessTokenInfo = null;
        try {
            accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            throw new EduException("获取access_token失败", 20001);
        }
        // 从accessTokenInfo获取出两个值
        // 把accessTokenInfo字符串转换成Map 根据key来获取value
        // 使用Gson解析
        Gson gson = new Gson();
        HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
        String accessToken = (String) mapAccessToken.get("access_token");
        String openid = (String) mapAccessToken.get("openid");
        //查询数据库当前用用户是否曾经使用过微信登录
        UcenterMember member = ucenterMemberService.getOpenId(openid);
        if (member == null) {
            System.out.println("新用户注册");
            // 拿着得到的access_token 和openId去请求微信固定的地址 获取扫描人的信息
            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            // 拼接两个参数
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            // 使用httpclient 发送请求 得到返回结果
            String userInfo = null;
            try {
                userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultUserInfo==========" + userInfo);
            } catch (Exception e) {
                throw new EduException("获取用户信息失败", 20001);
            }
            HashMap mapUserInfo = gson.fromJson(userInfo, HashMap.class);
            String nickname = (String) mapUserInfo.get("nickname");
            String headImgUrl = (String) mapUserInfo.get("headimgurl");
            // 根据openId判断数据库是否有相同的微信信息

            //向数据库中插入一条记录
            member = new UcenterMember();
            member.setNickname(nickname);
            member.setOpenid(openid);
            member.setAvatar(headImgUrl);
            ucenterMemberService.save(member);
        }
        // 生成jwt
        String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());

        //存入cookie
        //CookieUtils.setCookie(request, response, "guli_jwt_token", token);

        //因为端口号不同存在蛞蝓问题，cookie不能跨域，所以这里使用url重写
        return "redirect:http://localhost:3000?token=" + token;
    }

    @GetMapping("login")
    public String getWxCode(HttpSession session) {

        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址 获取业务服务器重定向地址
        String redirectUrl = constantPropertiesUtil.getRedirectUrl();
        try {
            //url编码
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new EduException(e.getMessage(), 20001);
        }

        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        //为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名
        String state = "rz";
        System.out.println("state = " + state);

        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                constantPropertiesUtil.getAppId(),
                redirectUrl,
                state);

        return "redirect:" + qrcodeUrl;
    }
}
